<script setup>
import {inject, onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {doGet, doPost} from "../http/httpRequest.js";
import {showMessage} from "../util/utils.js";

//定义router对象，该对象中提供了一些路由方法供我们使用，比如router.push(), router.go()
let router = useRouter();
//定义route对象，该对象提供了一些路由属性/字段供我们使用，比如route.path;  route.params; 等等
let route = useRoute();

let clueDetail = ref({
  ownerDO : {},
  activityDO : {},
  appellationDO : {},
  needLoanDO : {},
  intentionStateDO : {},
  intentionProductDO : {},
  stateDO : {},
  sourceDO : {}
})

let clueRemark = ref({})
let clueRemarkRules = ref({
  noteContent : [
    { required: true, message: '跟踪内容不能为空', trigger: 'blur' },
    { min: 5, max: 255, message: '跟踪内容长度为5-255位', trigger: 'blur' }
  ],
  noteWay : [
    { required: true, message: '请选择跟踪方式', trigger: ['blur', 'change'] }
  ]
})

onMounted(() => {
  loadClue()
  loadClueRemarkByPage(1)
})

//根据id加载线索详情数据
const loadClue = () => {
  let clueId = route.params.clueId;
  doGet('/api/clue/info/' + clueId, {}).then(resp => {
    if (resp.data.code === 200) {
      clueDetail.value = resp.data.data;
    } else {
      showMessage('数据加载失败', 'error');
    }
  })
}

//联系方式的对象数组，初始值是空
let noteWayOptions = ref([{}])

//根据字典类型code加载字典值数据
const loadDicValue = (typeCode) => {
  doGet('/api/dic/'+ typeCode, {}).then(resp => {
    if (resp.data.code === 200) {
      if (typeCode === 'noteWay') {
        noteWayOptions.value = resp.data.data.dicValueDOList;
      }
    }
  })
}

//定义form的ref属性对象
let clueRemarkFormRef = ref()

//注入刷新函数
let flushPage = inject('flush');

//线索跟踪记录提交
const clueRemarkSubmit = (formEl) => {
  if (!formEl) { //如果formEl不存在，也就是你没有给login()函数传userFormRef参数，那么就return，不做验证了
    return
  }
  formEl.validate((valid) => {
    if (valid) { //valid是true表示验证通过，否则没通过
      doPost('/api/clue/remark', {
        clueId : clueDetail.value.id, //线索id
        noteWay : clueRemark.value.noteWay, //跟踪方式
        noteContent : clueRemark.value.noteContent //跟踪内容
      }).then(resp => {
        if (resp.data.code === 200) {
          showMessage('跟踪记录提交成功', 'success');
          //页面局部刷新
          flushPage();
        } else {
          showMessage('跟踪记录提交失败，原因：' + resp.data.msg, 'error');
        }
      })
    }
  })
}

//线索跟踪记录的list，初始值是空
let clueRemarkList = ref([{
  noteWayDO : {},
  createByDO : {},
  editByDO : {}
}])
//分页时总共有多少条数据
let total = ref(0)
//分页时每页显示多少条数据
let pageSize = ref(0)

//根据线索id查询该线索的跟踪记录（分页查询）
const loadClueRemarkByPage = (current) => {
  let clueId = route.params.clueId
  doGet('/api/clue/remarks', {
    current : current,
    clueId : clueId
  }).then(resp => {
    if (resp.data.code === 200) {
      clueRemarkList.value = resp.data.data.list;
      total.value = resp.data.data.total;
      pageSize.value = resp.data.data.pageSize;
    } else {
      showMessage('数据加载失败', 'error');
    }
  })
}

//分页函数
const toPage = (value) => {
  loadClueRemarkByPage(value);
}

const goBack = () => {
  router.back();
}

let convertCustomerVisible = ref(false)
//转换客户
const convertCustomer = () => {
  convertCustomerVisible.value = true
}

let customerQuery = ref({})
let customerRules = ref({
  product : [
    { required: true, message: '请选择意向产品', trigger: 'blur' }
  ],
  description : [
    { min: 5, max: 255, message: '客户描述长度为5-255个字符', trigger: 'blur' }
  ],
  nextContactTime : [
    { required: true, message: '请选择下次跟踪时间', trigger: 'blur' }
  ]
})
let productOptions = ref([{}])

let clueFormRef = ref();
//线索转换客户提交
const convertCustomerSubmit = (formEL) => {
  if (!formEL) { //如果formEl不存在，也就是你没有给login()函数传userFormRef参数，那么就return，不做验证了
    return
  }
  formEL.validate((valid) => {
    if (valid) { //valid是true表示验证通过，否则没通过
      doPost('/api/customer', {
        clueId : clueDetail.value.id,
        product : customerQuery.value.product,
        description : customerQuery.value.description,
        nextContactTime : customerQuery.value.nextContactTime
      }).then(resp => {
        if (resp.data.code === 200) {
          showMessage('转换成功', 'success')
          //跳转到客户列表页
          router.push('/dashboard/customer')
        } else {
          showMessage('转换失败，原因：' + resp.data.msg, 'success')
        }
      })
    }
  })
}

//加载在售的产品
const loadProduct = () => {
  doGet('/api/product/onsale', {}).then(resp => {
    if (resp.data.code === 200) {
      productOptions.value = resp.data.data;
    }
  })
}
</script>

<template>
  <el-form
      ref="clueRemarkFormRef"
      :model="clueRemark"
      label-width="110px"
      :rules="clueRemarkRules">

    <el-form-item label="负责人">
      <div class="desc">{{clueDetail.ownerDO.name}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="所属活动">
      <div class="desc">{{clueDetail.activityDO.name}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="姓名">
      <div class="desc">{{clueDetail.fullName}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="称呼">
      <div class="desc">{{clueDetail.appellationDO.typeValue}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="手机">
      <div class="desc">{{clueDetail.phone}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="微信">
      <div class="desc">{{clueDetail.weixin}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="QQ">
      <div class="desc">{{clueDetail.qq}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="邮箱">
      <div class="desc">{{clueDetail.email}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="年龄">
      <div class="desc">{{clueDetail.age}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="职业">
      <div class="desc">{{clueDetail.job}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="年收入">
      <div class="desc">{{clueDetail.yearIncome}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="住址">
      <div class="desc">{{clueDetail.address}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="贷款">
      <div class="desc">{{clueDetail.needLoanDO.typeValue}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="意向状态">
      <div class="desc">{{clueDetail.intentionStateDO.typeValue}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="意向产品">
      <div class="desc">{{clueDetail.intentionProductDO.name}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="线索状态">
      <div class="desc">{{clueDetail.stateDO.typeValue}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="线索来源">
      <div class="desc">{{clueDetail.sourceDO.typeValue}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="线索描述">
      <div class="desc">{{clueDetail.description}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="下次联系时间">
      <div class="desc">{{clueDetail.nextContactTime}}&nbsp;</div>
    </el-form-item>

    <el-form-item label="填写跟踪记录" prop="noteContent">
      <el-input
          v-model="clueRemark.noteContent"
          :rows="8"
          maxlength="255"
          show-word-limit
          type="textarea"/>
    </el-form-item>
    <el-form-item label="跟踪方式" prop="noteWay">
      <el-select
          v-model="clueRemark.noteWay"
          placeholder="请选择跟踪方式"
          style="width: 100%"
          @click="loadDicValue('noteWay')"
          clearable>
        <el-option
            v-for="item in noteWayOptions"
            :key="item.id"
            :label="item.typeValue"
            :value="item.id"/>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="clueRemarkSubmit(clueRemarkFormRef)">提 交</el-button>
      <el-button type="success" @click="convertCustomer">转换客户</el-button>
      <el-button type="success" plain @click="goBack">返 回</el-button>
    </el-form-item>

    <el-form-item label="历史跟踪记录">
      <el-table
          :data="clueRemarkList"
          style="width: 100%">
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column property="noteWayDO.typeValue" label="跟踪方式"/>
        <el-table-column property="noteContent" label="跟踪内容"/>
        <el-table-column property="createTime" label="创建时间"/>
        <el-table-column property="createByDO.name" label="创建人"/>
        <el-table-column property="editTime" label="编辑时间"/>
        <el-table-column property="editByDO.name" label="编辑人"/>
        <el-table-column label="操作" width="90">
          <template #default="scope">
            <a href="javascript:void(0)" style="margin-right: 8px;" @click="edit(scope.row.id)">编辑</a>
            <a href="javascript:void(0)" @click="del(scope.row.id)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <br/>
      <el-pagination :background="true"
                     layout="prev, pager, next, jumper, ->, total"
                     :total="total"
                     :page-size="pageSize"
                     @current-change="toPage"/>
    </el-form-item>
  </el-form>

  <!-- 转换客户的蒙版弹层对话框 -->
  <el-dialog v-model="convertCustomerVisible" title="转换客户" width="800" center>
    <el-form ref="clueFormRef" :model="customerQuery" label-width="auto" :rules="customerRules">
      <el-form-item label="意向产品" prop="product">
        <el-select v-model="customerQuery.product" placeholder="请选择意向产品" @click="loadProduct">
          <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="客户描述" prop="description">
        <el-input
            v-model="customerQuery.description"
            :rows="8"
            type="textarea"
            maxlength="255"
            show-word-limit
            placeholder="请输入活动描述"/>
      </el-form-item>

      <el-form-item label="下次跟踪时间" prop="nextContactTime">
        <el-date-picker
            v-model="customerQuery.nextContactTime"
            type="datetime"
            placeholder="请选择下次跟踪时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="convertCustomerVisible = false">关 闭</el-button>
        <el-button type="primary" @click="convertCustomerSubmit(clueFormRef)">转 换</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.desc {
  background: azure;
  width: 100%;
  margin-left: 10px;
  padding-left: 10px;
}
.el-table {
  margin-bottom: 15px;
}
</style>